package com.sdk.bigdata.utils;

import com.alibaba.fastjson.JSONObject;
import com.sdk.bigdata.constant.Constants;
import com.sdk.bigdata.http.BigDataHttpRequest;
import com.sdk.bigdata.http.BigDataHttpResponseResult;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

public class OkHttpUtils {
    private final static Integer retry_count = 3;
    private final static Logger logger = LoggerFactory.getLogger(OkHttpUtils.class);

    public static BigDataHttpResponseResult doPost(BigDataHttpRequest request, String url, Integer timeoutMillSeconds) {
        BigDataHttpResponseResult responseResult = new BigDataHttpResponseResult();
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(timeoutMillSeconds, TimeUnit.MILLISECONDS)
                .build();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), JSONObject.toJSONString(request));
        Request request1 = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        int retryCount = retry_count;
        while (retryCount-- > 0) {
            try {
                Response response = okHttpClient.newCall(request1).execute();
                if (null != response.body()) {
                    responseResult = JSONObject.parseObject(response.body().string(), BigDataHttpResponseResult.class);
                    if (responseResult.getCode().equals("0")) {
                        return responseResult;
                    }
                }
            } catch (IOException e) {
                LoggerUtil.log(logger, Constants.ERROR, "flushForData,数据处理中,异常为:" + e);
            }
            if (retryCount > 1) {
                // 休眠500 ms
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ignore) {
                }
            }
        }
        return responseResult;
    }

    public static int ping(String address) throws IOException {
        int status;
        URL urlObj;
        urlObj = new URL(address);
        HttpURLConnection oc = (HttpURLConnection) urlObj.openConnection();
        oc.setUseCaches(false);
        oc.setConnectTimeout(3000); // 设置超时时间
        status = oc.getResponseCode();// 请求状态
        return status;
    }
}
